package org.linlinjava.litemall.web.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.linlinjava.litemall.core.constant.LitemallWXMembershipLevelConstants;
import org.linlinjava.litemall.core.notify.NoticeHelper;
import org.linlinjava.litemall.core.util.AdminCouponDateUtil;
import org.linlinjava.litemall.core.util.GeneratorUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.dto.WebOrderGoodsRemarkDTO;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.web.dto.WebPointExchangeOrderDTO;
import org.linlinjava.litemall.web.vo.WebExchangeGoodsVo;
import org.linlinjava.litemall.web.vo.WebGoodsAndExchangeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static org.linlinjava.litemall.db.beans.Constants.MEMBER_STATUS_INUSE;
@Service
public class WebPointExchangeService {

    @Autowired
    private LumierePointExchangeService lumierePointExchangeService;

    @Autowired
    private LitemallCategoryService litemallCategoryService;

    @Autowired
    private LitemallGoodsService litemallGoodsService;

    @Autowired
    private LitemallGoodsSpecificationService litemallGoodsSpecificationService;

    @Autowired
    private LitemallGoodsAccessoryService litemallGoodsAccessoryService;

    @Autowired
    private LitemallGoodsPropertyService litemallGoodsPropertyService;

    @Autowired
    private LitemallUserService litemallUserService;

    @Autowired
    private LitemallOrderService orderService;

    @Autowired
    private LitemallAddressService litemallAddressService;

    @Autowired
    private LitemallGoodsProductService litemallGoodsProductService;

    @Autowired
    private LitemallOrderGoodsService litemallOrderGoodsService;

    @Autowired
    private LitemallOrderGoodsPropertyService litemallOrderGoodsPropertyService;

    @Autowired
    private LitemallOrderGoodsAccessoryService litemallOrderGoodsAccessoryService;

    @Autowired
    private LitemallIntegralLogService integralLogService;

    @Autowired
    private LumiereLevelMemberPointService lumiereLevelMemberPointService;

    @Autowired
    private LumierelLevelMemberService lumierelLevelMemberService;

    @Autowired
    private LumiereMemberWelfareCouponService lumiereMemberWelfareCouponService;

    @Autowired
    private LitemallCouponService litemallCouponService;

    @Autowired
    private LitemallCouponUserService litemallCouponUserService;

    @Autowired
    private LumiereMemberWelfareSubscribeService lumiereMemberWelfareSubscribeService;

    @Autowired
    private LumiereSubscribeUserService lumiereSubscribeUserService;

    @Autowired
    private LitemallGiftCardService litemallGiftCardService;

    @Autowired
    private LitemallGiftCardUserService litemallGiftCardUserService;

    @Autowired
    private LumiereSubscribeRuleService lumiereSubscribeRuleService;

    @Autowired
    private NoticeHelper noticeHelper;

    @Autowired
    private LitemallGoodsRegionService goodsRegionService;

    @Autowired
    private LitemallShopRegionService shopRegionService;

    @Autowired
    private LumiereCouponStrategyService lumiereCouponStrategyService;
    @Autowired
    private LumiereCouponUserService lumiereCouponUserService;

    public Object categoryPointExchange(Integer pointExchangeId){
          // List<LumierePointExchange> categories =  lumierePointExchangeService.listCategory();
        // 这里我们引入了两个静态方法，以及通过 TreeSet<> 来达到获取不同元素的效果
//        List<CategoryVo> vos = categories.stream().collect(
//                collectingAndThen(
//                        toCollection(() -> new TreeSet<>(Comparator.comparing(LumierePointExchange::getCategoryId))), ArrayList::new)
//        ).stream().map(category ->{
//            LitemallCategory c = litemallCategoryService.findById(category.getCategoryId());
//            CategoryVo vo = new CategoryVo();
//            vo.setName(c != null ? c.getName() : null);
//            vo.setId(category.getCategoryId());
//            return vo;
//        }).collect(Collectors.toList());

        //查询兑换
        LumierePointExchange exchange =  lumierePointExchangeService.findById(pointExchangeId);
        if(exchange == null){
            return ResponseUtil.fail(222,"积分兑换不存在");
        }
        /*Integer categoryId = exchange.getCategoryId();
        //通过分类查询商品
        LitemallCategory category = litemallCategoryService.findById(categoryId);
        List<LitemallCategory> categoryLv3 = new ArrayList<>();
        categoryLv3 =  listCategoryLv3(category,categoryLv3);*/
        //循环三级分类
       return ResponseUtil.okList(litemallCategoryService.findByIds(exchange.getCategoryIds()));
    }

    /**
     * 通过三级分类查询对应的积分兑换
     * @param categoryId
     * @return
     */
    public Object pointExchangeByCategoryId(Integer categoryId,Integer pointExchangeId,Integer shopId){

        if( categoryId == null){
            return ResponseUtil.fail(333,"三级分类Id不能为空");
        }

        //定义一个集合存储商品信息
        List<WebExchangeGoodsVo> vos = new ArrayList<>();

        //根据分类查出对应的积分兑换
//        List<LumierePointExchange> exchanges = lumierePointExchangeService.listByCategory(categoryId);
        LumierePointExchange exchange = lumierePointExchangeService.findById(pointExchangeId);

        //根据分类查出所有的商品
        List<LitemallGoods> goods = litemallGoodsService.findByCategoryIdAndShopId(categoryId,shopId);

        //过滤掉在门店中不存在的商品
        goods = goods.stream().filter(good -> {
            List<LitemallGoodsRegion> goodsRegions = goodsRegionService.queryByGid(good.getId());
            List<Integer> cityIds = goodsRegions.stream().map(LitemallGoodsRegion::getCityId).collect(Collectors.toList());
            List<LitemallShopRegion> shopRegions = shopRegionService.queryByShopIdAndRegionIds(shopId, cityIds);

            if (shopRegions != null && shopRegions.size() > 0) {
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());

        goods.stream().forEach(good -> {
            WebExchangeGoodsVo vo = new WebExchangeGoodsVo();
                vo.setGoodsId(good.getId());
                vo.setGoodsName(good.getName());
                vo.setMinMoney(exchange.getMinMoney());
                vo.setMaxMoney(exchange.getMaxMoney());
                vo.setPicUrl(good.getPicUrl());
                vo.setPoints(new BigDecimal(exchange.getPoint()));
                vo.setPointExchangeId(exchange.getId());
                vos.add(vo);
        });

        return ResponseUtil.okList(vos);
    }

    /**
     * 查询商品信息，规格，属性，添加辅料
     * @param goodsId
     * @return
     */
    public Object goodDetailAndExchange(Integer goodsId,Integer pointExchangeId){
        //积分兑换
        LumierePointExchange exchange = lumierePointExchangeService.findById(pointExchangeId);
        Assert.isTrue(ObjectUtil.isNotNull(exchange), JSON.toJSONString(ResponseUtil.fail(4445,"积分兑换不存在")));
        WebGoodsAndExchangeVo vo = new WebGoodsAndExchangeVo();
        vo.setAccessories( litemallGoodsAccessoryService.queryByGoodsId(goodsId));
        vo.setProperties(litemallGoodsPropertyService.queryByGoodsId(goodsId));
        vo.setSpecifications(litemallGoodsSpecificationService.queryByGid(goodsId));
        vo.setMaxMoney(exchange.getMaxMoney());
        vo.setMinMoney(exchange.getMinMoney());
        return ResponseUtil.ok(vo);
    }

    /**
     * 商品下单
     * @param dto
     * @return
     */
    public Object orderByPoint(WebPointExchangeOrderDTO dto,Integer shopId){
        //规格
        LitemallGoodsSpecification specification =  litemallGoodsSpecificationService.findById(dto.getSpecificationId());

        if(specification == null){
            return ResponseUtil.fail(4444,"商品规格不存在");
        }

        //属性
        List<LitemallGoodsProperty> properties = new ArrayList<>();
//        LitemallGoodsProperty property = litemallGoodsPropertyService.findById(dto.getPropertyVo().getGoodsPropertyId());
        for (int i = 0; i < dto.getPropertyVos().size(); i++) {
            LitemallGoodsProperty property = litemallGoodsPropertyService.findById(dto.getPropertyVos().get(i).getGoodsPropertyId());
            if(property == null){
                return ResponseUtil.fail(4444,"商品属性不存在");
            }
            properties.add(property);
        }


        //积分兑换
        LumierePointExchange exchange = lumierePointExchangeService.findById(dto.getPointExchangeId());

        if(exchange == null){
            return ResponseUtil.fail(4445,"积分兑换不存在");
        }

        //辅料价格
        BigDecimal accessoryPrice = BigDecimal.ZERO;
        //商品
        LitemallGoods goods = null;
        if (specification.getGoodsId() != null) {
            goods = litemallGoodsService.findById(specification.getGoodsId());
        }

        //判断账户积分是否足够
        LitemallUser user = litemallUserService.findById(dto.getUserId());
        if(user.getPoints().compareTo(new BigDecimal(exchange.getPoint())) < 0){
            return ResponseUtil.fail(732,"账户积分不足，商品兑换失败");
        }else{
            user.setPoints(user.getPoints().subtract(new BigDecimal(exchange.getPoint())));
        }

        //货品 商品在该门店是否有货
        List<LitemallGoodsProduct> products = litemallGoodsProductService.queryByGidAndSid(goods.getId(),shopId);

        if(products.size() == 0){
            products = litemallGoodsProductService.queryByGidAndSid(goods.getId(),null);

            if(products.size() == 0){
                return ResponseUtil.fail(733,"商品已售罄");
            }
        }

        List<LitemallOrderGoodsAccessory> accessories = new ArrayList<>();
        for (int i = 0; i < dto.getAccessoryVos().size(); i++) {
                LitemallGoodsAccessory accessory = litemallGoodsAccessoryService.findById(dto.getAccessoryVos().get(i).getAccessoryId());
                if(accessory == null){
                    return ResponseUtil.fail(555,"商品辅料不存在");
                }
                Integer num  = 1;
                if(accessory.getCostType() != 0 ){
                    num = dto.getAccessoryVos().get(i).getAccessoryNumber();
                }
                BigDecimal singleAccessoryPrice = accessory.getPrice() != null ? accessory.getPrice().multiply(new BigDecimal(num)).setScale(2,BigDecimal.ROUND_HALF_UP) : null;
                accessoryPrice = accessoryPrice.add(singleAccessoryPrice);    //辅料价格相加
                LitemallOrderGoodsAccessory accesss = new LitemallOrderGoodsAccessory();
                accesss.setPrice(singleAccessoryPrice);
                accesss.setGoodsId(specification.getGoodsId());
                accesss.setAccessoryName(accessory.getName());
                accesss.setNumber(dto.getAccessoryVos().get(i).getAccessoryNumber());
                accesss.setAccessoryId(accessory.getId());
                accesss.setAccessoryName(accessory.getName());
                accessories.add(accesss);
        }

        //校验商品总值是否超过了积分兑换的价值范围
        BigDecimal goodsPrice = BigDecimal.ZERO;
        if(specification != null){
            goodsPrice = goodsPrice.add(specification.getPrice());
        }
        goodsPrice = goodsPrice.add(accessoryPrice);

        if(goodsPrice.subtract(exchange.getMinMoney()).compareTo(BigDecimal.ZERO) < 0
                || goodsPrice.subtract(exchange.getMaxMoney()).compareTo(BigDecimal.ZERO) > 0){
            return ResponseUtil.fail(556,"兑换商品的价格范围在["+exchange.getMinMoney()+"-"+exchange.getMaxMoney()+"]");
        }

        //加入到订单
        LitemallOrder order = new LitemallOrder();
        order.setShopId(shopId);
        order.setOrderType(dto.getOrdertype());
        LitemallAddress address = litemallAddressService.findDefault(dto.getUserId());
        Integer addressId  = null;
//        if(address != null ){
//            addressId = address.getId();
//        }
        if (addressId != null) {
            if (address != null) {
                String addressStr = address.getCountry() + address.getProvince() + address.getCity() + address.getCounty() + address.getAddressDetail();
                order.setAddress(addressStr);
                order.setMobile(address.getTel());
                order.setConsignee(user.getNickname());
            }
        } else {
            order.setConsignee("");
            order.setMobile("");
            order.setAddress("");
        }
        order.setPayType(Constants.PAY_TYPE_POINT_EXCHANGE);
        order.setPayTime(LocalDateTime.now());
        order.setOrderSource(Constants.ORDER_SOURCE_POS);
        order.setActualPrice(BigDecimal.ZERO);
        order.setIntegralPrice(goodsPrice);
        order.setPoints(new BigDecimal(exchange.getPoint()));
        order.setExId(exchange.getId());
        order.setGoodsPrice(goodsPrice);

        //TODO 订单的配送方式
//        order.setOrderType()
        order.setOrderSn(orderService.generateOrderSn(user.getId()));
        order.setUserId(user.getId());
        order.setFreightPrice(new BigDecimal(0.00));
        order.setCouponPrice(new BigDecimal(0.00));
        order.setIntegralPrice(new BigDecimal(0.00));
        order.setOrderStatus(Constants.ORDER_STATUS_ONGOING);
        order.setMadeStatus((byte)0);
        order.setShipStatus(Constants.SHIP_STATUS_NOT_SEND_OUT);
        order.setMobile(user != null ? user.getMobile() : null);

        //属性
        orderService.add(order);
        LitemallOrderGoods orderGoods = null;
        if(goods != null){
            /**
             * 设置订单商品项
             */
             orderGoods = new LitemallOrderGoods();
            orderGoods.setShopId(shopId);
            if(dto.getSpecificationId() != null){
                Integer[] specificationIds = new Integer[1];
                specificationIds[0]= dto.getSpecificationId();
                orderGoods.setSpecificationIds(specificationIds);
                /**
                 * 这里应该插入规格名数组，待修改
                 */
                List<String> specs = new ArrayList<>();
                for (int i = 0; i < specificationIds.length; i++) {
                    LitemallGoodsSpecification byId = litemallGoodsSpecificationService.findById(specificationIds[i]);
                    if(byId != null){
                        specs.add(byId.getSpecification());
                    }
                }
                orderGoods.setSpecifications(specs.toArray(new String[specificationIds.length]));
            }
            List<WebOrderGoodsRemarkDTO> remarkList=new ArrayList<>();

            remarkList.add(WebOrderGoodsRemarkDTO.builder().index(0).content("").indexMakeStatus(0).build());

            orderGoods.setRemark(remarkList);
            //orderGoods.setRemark(dto.getRemark()==null?"": dto.getRemark().toString());
            orderGoods.setGoodsId(goods.getId());
            orderGoods.setCategoryId(goods.getCategoryId());
            orderGoods.setGoodsName(goods.getName());
            orderGoods.setGoodsSn(goods.getGoodsSn());
            orderGoods.setOrderId(order.getId());
            orderGoods.setProductId(products.get(0).getId());
            orderGoods.setNumber((short) 1);
            orderGoods.setPicUrl(goods.getPicUrl());
            orderGoods.setPrice(goodsPrice);
            orderGoods.setTaxPrice(BigDecimal.ZERO);
            litemallOrderGoodsService.add(orderGoods);
        }else{
            return ResponseUtil.fail(123,"商品不存在");
        }
        for (int i = 0; i < properties.size(); i++) {
            LitemallOrderGoodsProperty proper = new LitemallOrderGoodsProperty();
            proper.setName(dto.getPropertyVos().get(i).getName());
            proper.setOrderGoodsId(orderGoods.getId());
            proper.setOrderId(order.getId());
            proper.setGoodsId(specification.getGoodsId());
            proper.setValue(dto.getPropertyVos().get(i).getValue());
            orderGoods.setOrderId(order.getId());
            proper.setOrderGoodsId(orderGoods.getId());
            proper.setOrderId(order.getId());
            proper.setGoodsPropertyId(dto.getPropertyVos().get(i).getGoodsPropertyId());
            litemallOrderGoodsPropertyService.add(proper);
        }
        LitemallOrderGoods finalOrderGoods = orderGoods;
        accessories.stream().forEach(accessory -> {
            accessory.setOrderId(order.getId());
            accessory.setOrderGoodsId(finalOrderGoods.getId());
            litemallOrderGoodsAccessoryService.add(accessory);
        });

        //更新用户积分
        litemallUserService.updateById(user);

        LitemallIntegralLog log = new LitemallIntegralLog();
        log.setUserId(dto.getUserId());
        log.setType(Constants.INTEGRAL_LOG_TYPE_MINUS);
        log.setPoints(user.getPoints());
        log.setChangePoints(new BigDecimal(exchange.getPoint()).multiply(new BigDecimal(-1)));
        log.setOrderId(order.getId());
        //添加详细信息
        log.setUseType(5);
        log.setGoodsName(litemallOrderGoodsService.queryByOid(order.getId()).stream().map(litemallOrderGoods -> litemallOrderGoods.getGoodsName()).collect(Collectors.toList()));
        integralLogService.add(log);

        //用户等级会员提升
        upgradeLevel(dto.getUserId(),user,exchange);

        //积分兑换消息通知
        String msg = "You recieved the " + exchange.getName();
        noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER, "Integral notification", msg , user.getId(), dto);

        //TODO 订单类型和门店Id
        return ResponseUtil.ok("商品兑换成功");
    }

    public Object listAllPointExchange(){
        List<LumierePointExchange> exchanges = lumierePointExchangeService.queryAll();
        return ResponseUtil.okList(exchanges);
    }

    /**
     * 递归查询三级分类
     */
    public List<LitemallCategory> listCategoryLv3(LitemallCategory category , List<LitemallCategory> categoryLv3){
        List<LitemallCategory> cc = litemallCategoryService.queryByPid(category.getId());

        if(cc.size() >0){
            for (int i = 0; i < cc.size(); i++) {
                List<LitemallCategory> cs =  litemallCategoryService.queryByPid(cc.get(i).getId());

                if(cs.size() == 0){
                    categoryLv3.add(cc.get(i));
                }else{
                    categoryLv3 =  listCategoryLv3(cc.get(i),categoryLv3);
                }
            }
        }else{
            categoryLv3.add(category);
        }
        return categoryLv3;
    }

    public void upgradeLevel(Integer userId,LitemallUser user,LumierePointExchange exchange){
        //判断使用积分是否足够升级
        //记录用户的积分
        LumiereLevelMember levelMember = lumierelLevelMemberService.findById(user.getUserLevel().intValue());
        List<LumiereLevelMemberPoint> points = lumiereLevelMemberPointService.listByUserId(userId);
        LumiereLevelMember upgradMember = lumierelLevelMemberService.queryByPidInDel(user.getUserLevel().intValue());
        //向上升级，查找升级的等级没有被删除，且状态为启用
        while (upgradMember != null && (upgradMember.getDeleted() == true || upgradMember.getStatus().equals(MEMBER_STATUS_INUSE) == false)) {
            upgradMember = lumierelLevelMemberService.queryByPid(upgradMember.getId());
        }
        if (points.size() == 0) {
            LumiereLevelMemberPoint point = new LumiereLevelMemberPoint();

            point.setStartTime(LocalDateTime.now());
            if (levelMember != null && levelMember.getExpiredDays() != 0) {
                point.setEndTime(LocalDateTime.of(LocalDate.now(), LocalTime.MAX).plusDays(levelMember.getExpiredDays()));
            }
            point.setUserId(userId);
            point.setAddTime(LocalDateTime.now());
            point.setUpdateTime(LocalDateTime.now());
            point.setConsumptionPoints(new BigDecimal(exchange.getPoint()));
            point.setDeleted(false);

            //如果没有符合条件的就不升级
            if ( upgradMember != null &&  (upgradMember.getDeleted() == false && upgradMember.getStatus().equals(MEMBER_STATUS_INUSE) == true)) {
                if (levelMember.getUpgradePoint() != null && levelMember.getUpgradePoint().compareTo(new BigDecimal(exchange.getPoint())) <= 0) {
                    user.setUserLevel(upgradMember.getId().byteValue());
                    //会员升级
                    litemallUserService.updateById(user);
                    point.setConsumptionPoints(new BigDecimal(0));
                    //用户等级会员升级，赠送福利
                    LocalDateTime endT = upgradMember.getExpiredDays() != null ? LocalDateTime.now().plusDays(upgradMember.getExpiredDays()) : null;
                    welfareGift(upgradMember.getId(), null, null, userId, upgradMember, endT);

                    //发送系统消息
                    noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER,
                            LitemallWXMembershipLevelConstants.WX_MEMBERSHIP_LEVEL_TITLE_NOTICEHELPER,
                            String.format(LitemallWXMembershipLevelConstants.WX_MEMBERSHIP_LEVEL_UPGRADE_NOTICEHELPER,upgradMember.getName()),userId,upgradMember);
                }
            }
            lumiereLevelMemberPointService.add(point);
        } else {
            //用户会员等级的变化"
            LumiereLevelMemberPoint point = points.get(0);
            BigDecimal nowPoint = point.getConsumptionPoints() == null ? BigDecimal.ZERO : point.getConsumptionPoints();
            if ( upgradMember != null && (upgradMember.getDeleted() == false && upgradMember.getStatus().equals(MEMBER_STATUS_INUSE) == true)) {
                if (levelMember.getUpgradePoint() != null && levelMember.getUpgradePoint().compareTo(new BigDecimal(exchange.getPoint()).add(nowPoint)) <= 0) {
                    user.setUserLevel(upgradMember.getId().byteValue());

                    litemallUserService.updateById(user);

                    //更改会员积分使用记录
                    if (upgradMember.getExpiredDays() != null && upgradMember.getExpiredDays() != 0) {
                        point.setStartTime(LocalDateTime.now());
                        point.setEndTime(LocalDateTime.now().plusDays(upgradMember.getExpiredDays()));
                    } else {
                        point.setEndTime(point.getEndTime());
                    }
                    point.setConsumptionPoints(new BigDecimal(0));

                    //用户等级会员升级，赠送福利
                    LocalDateTime endT = upgradMember.getExpiredDays() != null ? LocalDateTime.now().plusDays(upgradMember.getExpiredDays()) : null;
                    welfareGift(upgradMember.getId(), null, null, userId, upgradMember, endT);

                    //发送系统消息
                    noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER,
                            LitemallWXMembershipLevelConstants.WX_MEMBERSHIP_LEVEL_TITLE_NOTICEHELPER,
                            String.format(LitemallWXMembershipLevelConstants.WX_MEMBERSHIP_LEVEL_UPGRADE_NOTICEHELPER,upgradMember.getName()),userId,upgradMember);
                    point.setConsumptionPoints(BigDecimal.ZERO);
                } else {
                    point.setConsumptionPoints(nowPoint.add(new BigDecimal(exchange.getPoint())));
                    point.setEndTime(point.getEndTime());
                }
                lumiereLevelMemberPointService.update(point);
            }
        }
    }

    public void welfareGift(Integer memberId, LitemallUser giveeUser,
                            String userName, Integer userId, LumiereLevelMember levelMember, LocalDateTime endT) {

        //新优惠券
        List<LumiereCouponStrategy> lumiereCouponStrategies = lumiereCouponStrategyService.list(Wrappers.lambdaQuery(LumiereCouponStrategy.class)
                .eq(LumiereCouponStrategy::getCouponType, 5)
                .eq(LumiereCouponStrategy::getStatus, 1)
                .eq(LumiereCouponStrategy::getDeleted, 0));
        lumiereCouponStrategies.stream().forEach(lumiereCouponStrategy->{
            for (Integer levelMemberId : lumiereCouponStrategy.getLevelMember()){
                if(levelMemberId.equals(memberId)){
                    for(int i=1;i<=(lumiereCouponStrategy.getReleasedQuantity()==null?1:lumiereCouponStrategy.getReleasedQuantity());i++){
                        long nextId = IdUtil.getSnowflake(2, 2).nextId();
                        LocalDateTime[] localDateTimes = AdminCouponDateUtil.calculateExpirationTime(lumiereCouponStrategy);
                        //发放券
                        LumiereCouponUser coupon = LumiereCouponUser.builder()
                                .userId(userId)
                                .strategyId(lumiereCouponStrategy.getId())
                                .couponId(lumiereCouponStrategy.getCouponId())
                                .userName(userName)
                                .startTime(localDateTimes[0])
                                .endTime(localDateTimes[1])
                                .code(String.valueOf(nextId))
                                .addTime(LocalDateTime.now())
                                .updateTime(LocalDateTime.now())
                                .deleted(false)
                                .build();
                        lumiereCouponUserService.save(coupon);
                    }
                }
            }
        });

        //添加优惠券
        List<LumiereMemberWelfareCoupon> welfareCoupons = lumiereMemberWelfareCouponService.findByMemberId(memberId, (byte) 1);

        welfareCoupons.stream().forEach(welfareCoupon -> {
            Integer couponNum = welfareCoupon.getNumbers();
            LitemallCoupon coupon = litemallCouponService.findById(welfareCoupon.getCouponId());

            if (coupon != null) {
                LocalDateTime startT = coupon.getStartTime();
                LocalDateTime endTime = coupon.getEndTime();
                if(coupon.getTimeType().equals(0)){
                    startT = LocalDateTime.now();
                    endTime = startT.plusDays(coupon.getDays());
                }

                for (Integer i = 0; i < couponNum; i++) {
                    LitemallCouponUser litemallCouponUser = new LitemallCouponUser();
                    litemallCouponUser.setStartTime(startT);
                    litemallCouponUser.setEndTime(endTime);
                    litemallCouponUser.setStatus((short) 0);
                    litemallCouponUser.setCouponId(coupon.getId());
                    litemallCouponUser.setAddTime(LocalDateTime.now());
                    litemallCouponUser.setUpdateTime(LocalDateTime.now());
                    litemallCouponUser.setDeleted(false);
                    litemallCouponUser.setUserId(giveeUser != null ? giveeUser.getId() : userId);
                    litemallCouponUser.setUserName(userName);
                    litemallCouponUserService.add(litemallCouponUser);
                }
            }
        });

        //添加用户订阅
        List<LumiereMemberWelfareSubscribe> welfareSubscribes = lumiereMemberWelfareSubscribeService.findByMemberId(memberId, (byte) 1);

        welfareSubscribes.stream().forEach(welfareSubscribe -> {
            Integer[] selectRuleIds = welfareSubscribe.getSubscribeRuleIds();
            LumiereSubscribeUser subscribeUser = addSubscribeUser(userId, welfareSubscribe.getSubscribeId(), selectRuleIds, endT, userName, giveeUser);
            lumiereSubscribeUserService.add(subscribeUser);
        });


        //添加礼物卡
        if (levelMember.getGiftCardIds() != null) {
            Integer[] giftCardIds = levelMember.getGiftCardIds();
            for (int i = 0; i < giftCardIds.length; i++) {
                LitemallGiftCard litemallGiftCard = litemallGiftCardService.findById(giftCardIds[i]);
                if (litemallGiftCard != null) {
                    LitemallGiftCardUser giftCardUser = new LitemallGiftCardUser();
                    giftCardUser.setIsDefault(0);

                    String cardNumber = GeneratorUtil.cardNumberGenerator("00", userId);
                    LitemallGiftCardUser cardUser = litemallGiftCardUserService.findByNumber(cardNumber);
                    while (cardUser != null) {
                        cardNumber = GeneratorUtil.cardNumberGenerator("00", userId);
                        cardUser = litemallGiftCardUserService.findByNumber(cardNumber);
                    }
                    giftCardUser.setCardNumber(cardNumber);
                    giftCardUser.setUserId(giveeUser != null ? giveeUser.getId() : userId);
                    giftCardUser.setAmount(BigDecimal.ZERO);
                    giftCardUser.setStatus(0);
                    giftCardUser.setDeleted(false);
                    giftCardUser.setAddTime(LocalDateTime.now());
                    giftCardUser.setUpdateTime(LocalDateTime.now());
                    giftCardUser.setGiftCardId(giftCardIds[i]);
                    litemallGiftCardUserService.add(giftCardUser);
                }
            }
        }

    }

    public LumiereSubscribeUser addSubscribeUser(Integer userId, Integer subscribeId, Integer[] selectRuleIds,
                                                 LocalDateTime endT, String givee, LitemallUser giveeUser) {

        LitemallUser user = litemallUserService.findById(userId);

        LumiereSubscribeUser lumiereSubscribeUser = new LumiereSubscribeUser();
        lumiereSubscribeUser.setPurchaserId(userId);
        if (lumiereSubscribeUser.getUserId() == null) {
            lumiereSubscribeUser.setUserId(giveeUser != null ? giveeUser.getId() : userId);
        }

        LumiereSubscribeRule rule = lumiereSubscribeRuleService.findById(selectRuleIds[0]);

        lumiereSubscribeUser.setSubscribeId(subscribeId);

        lumiereSubscribeUser.setStatus(Constants.SUBSCRIBE_USER_MEMBER_NOT_CONFIRM);

        lumiereSubscribeUser.setAutoSub(false);

        lumiereSubscribeUser.setPurchaserId(giveeUser != null ? giveeUser.getId() : userId);

        lumiereSubscribeUser.setUserName(giveeUser != null ? giveeUser.getUsername() : user != null ? user.getUsername() : null);

        lumiereSubscribeUser.setPrice(BigDecimal.ZERO);

        lumiereSubscribeUser.setStartTime(LocalDateTime.now());

        if(rule != null) {
            if (rule.getRuleType().equals((byte) 1)) {
                lumiereSubscribeUser.setEndTime(LocalDateTime.now().plusWeeks(1));
            } else if (rule.getRuleType().equals((byte) 2)) {
                lumiereSubscribeUser.setEndTime(LocalDateTime.now().plusMonths(1));
            } else {
                lumiereSubscribeUser.setEndTime(LocalDateTime.now().plusYears(1));
            }
        }
        lumiereSubscribeUser.setRuleId(selectRuleIds[0]);

        return lumiereSubscribeUser;
    }

}
